package com.njupt.Tree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/11/26 10:05
 * @Description: 222. 完全二叉树的节点个数
 * @Version: 1.0
 */


public class CountNodes {

    /**
     * 线序遍历递归法
     * @param root
     * @return
     */
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        int leftNum = countNodes(root.left);
        int rightNum = countNodes(root.right);
        return leftNum + rightNum + 1;
    }

    /**
     * 层次遍历法
     * @param root
     * @return
     */
    public int countNodes1(TreeNode root){
        Deque<TreeNode> queue = new LinkedList<>();

        if(root == null) return 0;
        int count = 0;
        queue.addLast(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.pollFirst();
                count++;
                if(treeNode.left != null) queue.addLast(treeNode.left);
                if(treeNode.right != null) queue.addLast(treeNode.right);

            }
        }
        return count;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);

        CountNodes test = new CountNodes();
        int num = test.countNodes1(root);
        System.out.println(num);
    }
}
